<?php

class bottle extends controller_basic {
	
	// 获取我捞到/扔出去的瓶子
	function get_bottles() { 
		$uid				= isset($this->__params['uid']) 		? (int)$this->__params['uid'] 			: 0;
		$is_receive	= isset($this->__params['is_receive'])	? (int)$this->__params['is_receive']		: 0;
//		$offset		= isset($this->__params['offset']) 		? (int)$this->__params['offset']			: 0;
//		$max		= isset($this->__params['max']) 			? (int)$this->__params['max']				: 0;
		$this->output(array(
			'datas'	=> mdl_bottle_item::getInstance()->findItems($uid, $is_receive, 0, 20), // 最多拥有50个瓶子 in + out
			'nav'		=> $is_receive == 0 ? 'receive' : 'onlythrow',
			'sql'		=> mdl_bottle_item::getInstance()->getLastSql(),
		));
	}
	
	/**
	 *
	 * 返回code:
	 * 	-2: 捞失败
	 * 	-1: 没有用户ID
	 * ===============================
	 * @TODO: 每日捞瓶子数量限制
	 */
	function find() { // 捞 http://192.168.56.101:8088/g-bottle/?bottle-find
		$uid = isset($this->__params['uid']) ? (int)$this->__params['uid'] : 0;
		$data = array( );
		if(0 == $uid) $data['code'] = -1;
		else {
			
			$d = mdl_account_limit::getInstance()->get($uid, TODAY);
			$cot_pick = isset($d['pick']) ? $d['pick'] : 0;
			
			if($cot_pick <= 0) $data['code'] = -3;
			else {
				$res = mdl_bottle_item::getInstance()->findOne_rand($uid);
				$data = (
					mdl_account_limit::getInstance()->inde($uid, 'pick', false) &&
					!empty($res) && 
					mdl_bottle_item::getInstance()->setReceiveOwner($res['iid'], $uid)
				) ? array(
					'iid'		=> $res['iid'],
					'cont'	=> $res['content'],
					'time'	=> $res['created'],
					'cot'		=> $cot_pick,
					'code'	=> '0'
				) : array( 'code' => '-2', 'd' => $res );
			}
		}
		$this->output($data);
	}
	
	/**
	 * 第一次扔
	 * http://192.168.56.101:8088/g-bottle/?page-test
	 * ===============================
	 * 限制 140 字符长度
	 * 取消前后空格
	 * 返回code：
	 * 	-1：必须的参数为空
	 *   0：插入失败
	 *  >0: 新插入的id
	 */
	function send() {
		$uid = isset($this->__params['uid']) ? (int)$this->__params['uid'] : 0;
		$con = isset($this->__params['con']) ? trim(urldecode($this->__params['con'])) : '';
		
		$data = array();
		if(0 == $uid) 
			$data['code'] = -1;
		else {
		
			// 可扔的数量
			$d = mdl_account_limit::getInstance()->get($uid, TODAY);
			$cot_wine = isset($d['wine']) ? $d['wine'] : 0;
			
			if($cot_wine <= 0) $data['code'] = -3;
			else {
				$con_max = 140;
				$con = strlen($con) > $con_max ? substr($con, 0, $con_max) : $con;
				
				$data['code'] = mdl_account_limit::getInstance()->inde($uid, 'wine', false) ?
					mdl_bottle_item::getInstance()->makeOne($uid, $con) : -2;
			}
		}
		
		$this->output($data);
	}
	
	function resend() { // 不理会， 重新扔回大海
		$iid = isset($this->__params['iid']) ? (int)$this->__params['iid'] : 0;
		
		$data = (!$iid) ?
			-1 : (int)mdl_bottle_item::getInstance()->setReceiveOwner($iid);
			
		$this->output(array( 'code' => $data ));
	}
}